export interface ChannelNotification {
  id: string
  orderId: string
  orderType: 'payment' | 'refund'
  channelCode: string
  channelName: string
  merchantId: string
  merchantName: string
  notificationType: 'async' | 'sync'
  notificationUrl: string
  status: 'pending' | 'success' | 'failed' | 'timeout'
  requestBody: string
  responseBody?: string
  responseCode?: number
  retryCount: number
  maxRetryCount: number
  createTime: string
  updateTime: string
  notifyTime?: string
  nextRetryTime?: string
  errorMessage?: string
  remark?: string
}

// 生成指定范围内的随机数
const getRandomNumber = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

// 生成模拟数据
export const generateMockData = (count: number = 35): ChannelNotification[] => {
  const data: ChannelNotification[] = []
  const statuses: ChannelNotification['status'][] = ['pending', 'success', 'failed', 'timeout']
  const orderTypes: ChannelNotification['orderType'][] = ['payment', 'refund']
  const notificationTypes: ChannelNotification['notificationType'][] = ['async', 'sync']
  const channels = [
    { code: 'alipay_official', name: '支付宝官方' },
    { code: 'alipay_isv', name: '支付宝服务商' },
    { code: 'wechat_official', name: '微信官方' },
    { code: 'wechat_isv', name: '微信服务商' },
    { code: 'unionpay', name: '银联' },
    { code: 'leshua_alipay', name: '乐刷支付宝' },
    { code: 'leshua_wechat', name: '乐刷微信' }
  ]

  // 添加一些示例数据
  data.push(
    {
      id: 'CN202506031200001',
      orderId: 'P202506031200001',
      orderType: 'payment',
      channelCode: 'alipay_official',
      channelName: '支付宝官方',
      merchantId: 'M2025060311001',
      merchantName: '测试商户01',
      notificationType: 'async',
      notificationUrl: 'https://api.alipay.com/notify/payment',
      status: 'success',
      requestBody: JSON.stringify({
        orderId: 'P202506031200001',
        amount: 100.00,
        status: 'success',
        transactionId: '2025060312000000001',
        channelCode: 'alipay_official'
      }, null, 2),
      responseBody: JSON.stringify({
        code: '10000',
        msg: 'Success',
        sign: 'abc123...'
      }, null, 2),
      responseCode: 200,
      retryCount: 0,
      maxRetryCount: 3,
      createTime: '2025/6/3 12:00:15',
      updateTime: '2025/6/3 12:00:16',
      notifyTime: '2025/6/3 12:00:16',
      remark: '支付成功，渠道通知'
    },
    {
      id: 'CN202506031200002',
      orderId: 'R202506031200001',
      orderType: 'refund',
      channelCode: 'wechat_official',
      channelName: '微信官方',
      merchantId: 'M2025060311001',
      merchantName: '测试商户01',
      notificationType: 'async',
      notificationUrl: 'https://api.mch.weixin.qq.com/notify/refund',
      status: 'failed',
      requestBody: JSON.stringify({
        orderId: 'R202506031200001',
        refundAmount: 50.00,
        status: 'success',
        refundTransactionId: '2025060312000000101',
        channelCode: 'wechat_official'
      }, null, 2),
      responseCode: 500,
      retryCount: 2,
      maxRetryCount: 3,
      createTime: '2025/6/3 12:31:00',
      updateTime: '2025/6/3 12:31:30',
      notifyTime: '2025/6/3 12:31:30',
      nextRetryTime: '2025/6/3 12:36:30',
      errorMessage: '渠道服务器内部错误',
      remark: '退款成功，渠道通知失败'
    }
  )

  // 生成更多模拟数据
  for (let i = 3; i <= count; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const orderType = orderTypes[Math.floor(Math.random() * orderTypes.length)]
    const notificationType = notificationTypes[Math.floor(Math.random() * notificationTypes.length)]
    const channel = channels[Math.floor(Math.random() * channels.length)]
    const retryCount = status === 'success' ? 0 : getRandomNumber(0, 3)
    const createdTime = new Date(2025, 5, getRandomNumber(1, 30), getRandomNumber(0, 23), getRandomNumber(0, 59))
    const updatedTime = new Date(createdTime.getTime() + getRandomNumber(0, 3600000)) // 最多1小时后更新

    const orderPrefix = orderType === 'payment' ? 'P' : 'R'
    const orderId = `${orderPrefix}${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(i).padStart(6, '0')}`

    const requestData = orderType === 'payment'
      ? {
          orderId,
          amount: getRandomNumber(100, 10000) / 100,
          status: 'success',
          transactionId: `${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(getRandomNumber(100000000, 999999999))}`,
          channelCode: channel.code
        }
      : {
          orderId,
          refundAmount: getRandomNumber(50, 1000) / 100,
          status: 'success',
          refundTransactionId: `${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(getRandomNumber(100000000, 999999999))}`,
          channelCode: channel.code
        }

    // 根据渠道类型设置不同的通知URL
    const getNotificationUrl = (channelCode: string, orderType: string) => {
      const urls = {
        alipay_official: `https://api.alipay.com/notify/${orderType}`,
        alipay_isv: `https://openapi.alipay.com/gateway.do?method=notify`,
        wechat_official: `https://api.mch.weixin.qq.com/notify/${orderType}`,
        wechat_isv: `https://api.mch.weixin.qq.com/v3/notify/${orderType}`,
        unionpay: `https://gateway.95516.com/notify/${orderType}`,
        leshua_alipay: `https://api.leshua.com/notify/alipay/${orderType}`,
        leshua_wechat: `https://api.leshua.com/notify/wechat/${orderType}`
      }
      return urls[channelCode as keyof typeof urls] || `https://api.${channelCode}.com/notify/${orderType}`
    }

    const notification: ChannelNotification = {
      id: `CN${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(i).padStart(6, '0')}`,
      orderId,
      orderType,
      channelCode: channel.code,
      channelName: channel.name,
      merchantId: `M${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(getRandomNumber(1000, 9999))}`,
      merchantName: `商户${i}`,
      notificationType,
      notificationUrl: getNotificationUrl(channel.code, orderType),
      status,
      requestBody: JSON.stringify(requestData, null, 2),
      retryCount,
      maxRetryCount: 3,
      createTime: createdTime.toLocaleString(),
      updateTime: updatedTime.toLocaleString(),
      remark: `${orderType === 'payment' ? '支付' : '退款'}${channel.name}通知`
    }

    if (status === 'success') {
      const responseCodes = ['10000', '0', 'SUCCESS']
      notification.responseBody = JSON.stringify({
        code: responseCodes[Math.floor(Math.random() * responseCodes.length)],
        msg: 'Success',
        sign: `sign_${getRandomNumber(1000, 9999)}...`
      }, null, 2)
      notification.responseCode = 200
      notification.notifyTime = updatedTime.toLocaleString()
    } else if (status === 'failed') {
      notification.responseCode = getRandomNumber(400, 500)
      notification.notifyTime = updatedTime.toLocaleString()
      notification.errorMessage = getRandomNumber(1, 2) === 1 ? '渠道服务器内部错误' : '签名验证失败'
      if (retryCount < 3) {
        const nextRetry = new Date(updatedTime.getTime() + 5 * 60 * 1000) // 5分钟后重试
        notification.nextRetryTime = nextRetry.toLocaleString()
      }
    } else if (status === 'timeout') {
      notification.notifyTime = updatedTime.toLocaleString()
      notification.errorMessage = '渠道通知超时'
      if (retryCount < 3) {
        const nextRetry = new Date(updatedTime.getTime() + 5 * 60 * 1000) // 5分钟后重试
        notification.nextRetryTime = nextRetry.toLocaleString()
      }
    }

    data.push(notification)
  }

  return data
}

export const mockData = generateMockData()

// 增删改查
export function addChannelNotification(item: ChannelNotification) {
  mockData.unshift(item)
}

export function updateChannelNotification(id: string, item: Partial<ChannelNotification>) {
  const idx = mockData.findIndex(m => m.id === id)
  if (idx > -1) Object.assign(mockData[idx], item)
}

export function deleteChannelNotification(id: string) {
  const idx = mockData.findIndex(m => m.id === id)
  if (idx > -1) mockData.splice(idx, 1)
}

export function getChannelNotification(id: string): ChannelNotification | undefined {
  return mockData.find(m => m.id === id)
}

// 状态映射
export const statusMap = {
  pending: { text: '待通知', color: 'orange' },
  success: { text: '通知成功', color: 'success' },
  failed: { text: '通知失败', color: 'error' },
  timeout: { text: '通知超时', color: 'warning' }
}

// 订单类型映射
export const orderTypeMap = {
  payment: { text: '支付订单', color: 'blue' },
  refund: { text: '退款订单', color: 'red' }
}

// 通知类型映射
export const notificationTypeMap = {
  async: { text: '异步通知', color: 'green' },
  sync: { text: '同步通知', color: 'purple' }
}